package j19;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author chengshuai
 * @date 2021/4/9 21:25
 */
public class ABASolveDemo {
    static AtomicStampedReference<Integer> stamp = new AtomicStampedReference<>(100, 1);
    public static void main(String[] args) {
        System.out.println("解决问题");
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "第1次版本号：" + stamp.getStamp());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stamp.compareAndSet(100, 101, stamp.getStamp(), stamp.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "第2次版本号：" + stamp.getStamp());
            stamp.compareAndSet(101, 100, stamp.getStamp(), stamp.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "第3次版本号：" + stamp.getStamp());
        }, "t3").start();

        new Thread(() -> {
            int num = ABASolveDemo.stamp.getStamp();
            System.out.println(Thread.currentThread().getName() + "第1次版本号：" + num);
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean b = ABASolveDemo.stamp.compareAndSet(100, 2019, num, num + 1);
            System.out.println(Thread.currentThread().getName() + "\t修改成功否" + b + "当前实际版本号：" + stamp.getStamp());
            System.out.println(Thread.currentThread().getName() + "\t当前实际最新值：" +stamp.getReference().toString());
        }, "t4").start();
    }
}
